﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
namespace Async.Compute.Bound
{
public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        Text = "Synchronization Context Task Scheduler Demo";
        Visible = true;
        Width = 400;
        Height = 100;
        m_syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    }

    private readonly TaskScheduler m_syncContextTaskScheduler;

    private CancellationTokenSource m_cts;

    private int Sum(CancellationToken ct, int n)
    {

        int sum = 0;
        for (; n > 0; n--)
        {
            checked { sum += n; }
            Thread.Sleep(200);
            ct.ThrowIfCancellationRequested();
        }
        return sum;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (m_cts != null)
        {
            m_cts.Cancel();
            m_cts = null;
        }
        else
        {
            Text = "Operation running";
            m_cts = new CancellationTokenSource();
            //这个任务使用默认任务调度器,并在一个线程池线程上执行
            var t = new Task<int>(() => Sum(m_cts.Token, int.Parse(txtSum.Text)), m_cts.Token);
            t.Start();
            //这些任务使用同步上下文任务调度器,并在GUI线程上执行
            t.ContinueWith(task => txtResult.Text += "Result : " + task.Result + Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, m_syncContextTaskScheduler);

            t.ContinueWith(task => txtResult.Text += "Operation canceld" + Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, m_syncContextTaskScheduler);

            t.ContinueWith(task => txtResult.Text += "Operation faulted" + Environment.NewLine, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, m_syncContextTaskScheduler);
        }
    }
}
}
